package com.kele.test.rabbitmq.controller;

import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageDeliveryMode;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("producer05_reliable")
public class ProducerController_High5_Reliable {

    @Autowired
    RabbitTemplate rabbitTemplate;

    @GetMapping("sendMessage")
    public String sendMessage(){
        for(int i=0;i<200;i++){
            sendMessage1(i);
        }
        return "OK";
    }
    public String sendMessage1(Integer id){

        /*
        发送了 0次或者1次
         */

        System.out.println("发送之前先保存起来");
        String goodsId = "goodsId_" + id;
        CorrelationData correlationData = new CorrelationData();
        correlationData.setId("1905A_123");
        /*
        1、生产着消息持久化
        2 要求confirm
         */
        rabbitTemplate.setConfirmCallback((CorrelationData correlationData1,
                                           boolean ack,
                                           String cause)->{
            System.out.println(correlationData1.getId());
            System.out.println(ack);
            System.out.println(cause);
            System.out.println("把之前先保存起来 消息删除");
        });

        rabbitTemplate.setReturnCallback((Message message,
                                          int replyCode,
                                          String replyText,
                                          String exchange,
                                          String routingKey)->{
            System.out.println("退回来的消息");
            System.out.println(new String(message.getBody()));
            System.out.println(replyCode);
            System.out.println(replyText);
            System.out.println(exchange);
            System.out.println(routingKey);
        });

        rabbitTemplate.convertAndSend(
                "exchange_direct_reliable","reliable","Hello 1905A",
                (Message message)->{
                    message.getMessageProperties().setMessageId(goodsId);
                    message.getMessageProperties()
                            .setReceivedDeliveryMode(MessageDeliveryMode.PERSISTENT);
                    return message;
                },correlationData);

        return "OK";
    }
}
